<template>
  <div ref="wrapRef" :style="{ height, width }"></div>
</template>
<script lang="ts">
import { defineComponent, ref, nextTick, unref, onMounted } from 'vue';

export default defineComponent({
  name: 'AMap',
  props: {
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: 'calc(100vh - 78px)',
    },
  },
  setup() {
    const wrapRef = ref<HTMLDivElement | null>(null);
    let AMapSelf = (window as any).AMap;
    const Icon = new AMap.Icon({
      size: new AMap.Size(26, 35),
      image: 'gaodemap/poi-marker-default.png',
      imageSize: new AMap.Size(26, 35),
    });

    async function initMap() {
      const wrapEl = unref(wrapRef);
      if (!wrapEl) return;
      AMapSelf = new AMap.Map(wrapEl, {
        resizeEnable: true,
        zoom: 15, // 初始化缩放级别
        viewMode: '3D',
        center: [113.418786, 23.137], // 初始化中心点
        // 指定离线地图路径
        layers: [
          new AMap.TileLayer({
            visible: true,
            zIndex: 99,
            opacity: 1,
            getTileUrl: (a, b, c) => {
              //经纬度转换成本地瓦片所在路径
              let flag = '00000000';
              let zz = c;
              let z = 'L' + zz;
              let xx = a.toString(16);
              let x = 'C' + flag.substring(0, 8 - xx.length) + xx;
              let yy = b.toString(16);
              let y = 'R' + flag.substring(0, 8 - yy.length) + yy;
              return 'gaodemap/' + z + '/' + y + '/' + x + '.png';
            },
          }),
        ],
      });

      AMapSelf.setDefaultCursor('pointer');

      AMapSelf.on('click', (e) => {
        AMapSelf.clearMap();
        var marker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
          icon: Icon,
          offset: new AMap.Pixel(-13, -30),
        });
        AMapSelf.add(marker);
        var text = '您在 [ ' + e.lnglat.getLng() + ',' + e.lnglat.getLat() + ' ] 的位置双击了地图';
        alert(text);
      });
    }

    onMounted(() => {
      initMap();
    });

    return { wrapRef };
  },
});
</script>
